import classnames from 'classnames'
import { FC, useContext, useEffect, useState } from 'react'

import { Input } from 'antd'
import { DataContext } from '../../logic/DataContext'
import './index.scss'

interface Props {
  data: ShuDuNS.ShuDuData
}

interface ShuDuCellProps extends ShuDuNS.ShuDuDataItem {
  onChange: (value: any) => void
  className?: string
}
/**
 * 单个数独格子，正常情况下是数字，选中之后可以输入数字
 */
function ShuDuCell(props: ShuDuCellProps) {
  const { value, onChange, x, y, className = '', isOrigin = false } = props
  const [isFocus, setIsFocus] = useState(false)
  const { highLightNumber, setHighLightNumber } = useContext(DataContext)

  function handleChange(event: any) {
    let { value: eventValue } = event.target
    if (eventValue.length > 1) {
      eventValue = eventValue.split(' ')
      setHighLightNumber(0)
    } else {
      eventValue = ~~eventValue
      setHighLightNumber(eventValue)
    }
    // 因为实际的 xy 都是 +1 状态的，所以得处理一下
    onChange({ x: x - 1, y: y - 1, value: eventValue })
  }

  function handleClickCell() {
    if (typeof value === 'number') setHighLightNumber(value)
    if (isOrigin) return
    setIsFocus(true)
  }

  return (
    // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
    <div
      className={classnames('shuDuCell', {
        [className]: !!className,
        highLight: value && highLightNumber === value
      })}
      onClick={handleClickCell}
    >
      <p className="shuDuCell__value">{value === 0 ? '' : value}</p>
      {isFocus && (
        <Input
          autoFocus
          className="shuduCell__input"
          onBlur={() => setIsFocus(false)}
          value={value === 0 ? '' : value.toString()}
          onChange={handleChange}
          onPressEnter={() => setIsFocus(false)}
        />
      )}
    </div>
  )
}
const originData = [[], [], [], [], [], [], [], [], []]
// 单个数独结构
const ShuDuItem: FC<Props> = (props) => {
  const { data: origin } = props

  const [data, setData] = useState<ShuDuNS.ShuDuData>(originData)

  function handleValueChange(params: any) {
    const { x, y, value } = params
    setData((old) => {
      const clone = [...old]
      clone[x][y].value = value
      return clone
    })
  }

  useEffect(() => {
    if (origin.length > 0) setData(origin)
  }, [origin])

  // for 两次，创建数组
  return (
    <div className="singleShuDu">
      {data.map((item, index) => (
        <div key={index} className="singleRow">
          {item.map((item1, y) => (
            <ShuDuCell
              key={`${index}${y}`}
              {...item1}
              onChange={handleValueChange}
              className="singleItem"
            />
          ))}
        </div>
      ))}
    </div>
  )
}

export default ShuDuItem
